package com.yc.demo.d0316;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "Upload/*", value = "/Upload/*")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //获取资源地址
        String uri = request.getRequestURI();
        //提取文件名
        String fileName = uri.replaceAll(".+/Upload/(.+)", "$1");
        //设置返回的内容类型

        //html ==》text/html, jpg ==》image/jpeg
        String mimeType = request.getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);
        //将文件返回给浏览器
        //java.io流
        String path = UploadImageServlet.IMAGE_PATH + fileName;
        try(FileInputStream fis = new FileInputStream(path)){
            byte[] buffer = new byte[1024];
            int count;
            ServletOutputStream out = response.getOutputStream();
            while ((count = fis.read(buffer))> -1){
                out.write(buffer, 0, count);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
